const { cacheManager, CacheKeys } = require('../utils/cache');

/**
 * 通用缓存中间件
 * @param {Function} keyGenerator - 缓存键生成函数
 * @param {number} ttl - 缓存过期时间（秒）
 * @param {Function} condition - 缓存条件判断函数
 */
function cacheMiddleware(keyGenerator, ttl = 300, condition = null) {
  return async (req, res, next) => {
    try {
      // 检查是否满足缓存条件
      if (condition && !condition(req)) {
        return next();
      }

      // 生成缓存键
      const cacheKey = keyGenerator(req);

      // 尝试从缓存获取数据
      const cachedData = await cacheManager.get(cacheKey);
      if (cachedData) {
        if (process.env.ENABLE_CACHE_LOGS === 'true') {
          console.log(`💾 缓存命中: ${cacheKey}`);
        }
        return res.json(cachedData);
      }

      // 重写res.json方法以拦截响应数据
      const originalJson = res.json;
      res.json = function (data) {
        // 只缓存成功的响应
        if (data && data.success !== false) {
          cacheManager.set(cacheKey, data, ttl)
            .then(() => {
              if (process.env.ENABLE_CACHE_LOGS === 'true') {
                console.log(`💾 缓存设置: ${cacheKey}`);
              }
            })
            .catch(err => console.error('❌ 缓存设置失败:', err));
        }

        // 调用原始的json方法
        return originalJson.call(this, data);
      };

      next();
    } catch (error) {
      console.error('缓存中间件错误:', error);
      next();
    }
  };
}

/**
 * 商品列表缓存中间件
 */
const productListCache = cacheMiddleware(
  (req) => CacheKeys.PRODUCT_LIST({
    ...req.query,
    page: req.query.page || 1,
    limit: req.query.limit || 10
  }),
  300, // 5分钟缓存
  (req) => req.method === 'GET' // 只缓存GET请求
);

/**
 * 商品详情缓存中间件
 */
const productDetailCache = cacheMiddleware(
  (req) => CacheKeys.PRODUCT_DETAIL(req.params.id),
  600, // 10分钟缓存
  (req) => req.method === 'GET'
);

/**
 * 店铺列表缓存中间件
 */
const shopListCache = cacheMiddleware(
  (req) => CacheKeys.SHOP_LIST({
    ...req.query,
    page: req.query.page || 1,
    limit: req.query.limit || 10
  }),
  300,
  (req) => req.method === 'GET'
);

/**
 * 店铺详情缓存中间件
 */
const shopDetailCache = cacheMiddleware(
  (req) => CacheKeys.SHOP_DETAIL(req.params.id),
  600,
  (req) => req.method === 'GET'
);

/**
 * 店铺商品缓存中间件
 */
const shopProductsCache = cacheMiddleware(
  (req) => CacheKeys.SHOP_PRODUCTS(req.params.id, {
    ...req.query,
    page: req.query.page || 1,
    limit: req.query.limit || 10
  }),
  300,
  (req) => req.method === 'GET'
);

/**
 * 仪表板统计缓存中间件
 */
const dashboardStatsCache = cacheMiddleware(
  () => CacheKeys.DASHBOARD_STATS(),
  180, // 3分钟缓存
  (req) => req.method === 'GET'
);

/**
 * 销售趋势缓存中间件
 */
const salesTrendCache = cacheMiddleware(
  (req) => CacheKeys.SALES_TREND(req.query.period || '7d'),
  300,
  (req) => req.method === 'GET'
);

/**
 * 缓存失效中间件
 * 用于在数据更新后清除相关缓存
 */
function invalidateCache(patterns) {
  return async (req, res, next) => {
    // 重写响应方法以在成功响应后清除缓存
    const originalJson = res.json;
    res.json = function (data) {
      // 如果操作成功，清除相关缓存
      if (data && data.success !== false) {
        Promise.all(
          patterns.map(pattern => {
            if (typeof pattern === 'function') {
              pattern = pattern(req, data);
            }
            return cacheManager.delPattern(pattern);
          })
        ).then(() => {
          console.log('缓存清除完成:', patterns);
        }).catch(err => {
          console.error('缓存清除失败:', err);
        });
      }

      return originalJson.call(this, data);
    };

    next();
  };
}

/**
 * 商品相关缓存失效
 */
const invalidateProductCache = invalidateCache([
  'product:*',
  'shop:*:products:*',
  'dashboard:*'
]);

/**
 * 店铺相关缓存失效
 */
const invalidateShopCache = invalidateCache([
  'shop:*',
  'dashboard:*'
]);

/**
 * 订单相关缓存失效
 */
const invalidateOrderCache = invalidateCache([
  'order:*',
  'dashboard:*',
  'sales:*'
]);

module.exports = {
  cacheMiddleware,
  productListCache,
  productDetailCache,
  shopListCache,
  shopDetailCache,
  shopProductsCache,
  dashboardStatsCache,
  salesTrendCache,
  invalidateCache,
  invalidateProductCache,
  invalidateShopCache,
  invalidateOrderCache
};
